import React, { useState, useEffect, useRef } from 'react';
import _ from 'lodash';
import { connect } from 'umi';
import styles from './index.less';
import { Button, message, Spin, Drawer, Modal, Form } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { TABLE_COLUMNS_LIST, IN_TABLE_COLUMNS_LIST } from './helper';
import { useTRState } from '#/utils/trHooks';
import HeadBox from './components/HeadBox/index';
import DRBox from './components/DRBox/index';
import LinkedFormItem from './components/LinkedFormItem/index';
import DRFormItem from './components/DRFormItem/index';
import { HocModal, TRTable } from './SchemaRender';
import {
  taskTableData,
  deployTask,
  undeploy,
  deleteTask,
  addTask,
  taskDetail,
  updateTask,
  taskInstanceList,
  taskInstanceDetail,
} from './service';
import { tableDataSource } from './mock';

const { confirm } = Modal;

const TaskAdmin = (props) => {
  const { buttonPermissionCode } = props;

  const searchResetRef = useRef(null);

  useEffect(() => {
    getCurrentTableList(state.keyword, state.pagination.pageSize);
  }, []);

  const [state, setState] = useTRState({
    pageLoading: false,
    keyword: '',
    taskId: '',
    tableDataSource: [],
    instanceOpen: false,
    selectedRowKeys: [],
    selectedRowKeys1: [],
    pagination: {
      current: 1,
      pageSize: 20,
      total: tableDataSource.length,
    },
  });

  const [reset, setReset] = useState(false);
  const [open, setOpen] = useState(false);
  const [viewOpen, setViewOpen] = useState(false);
  const [viewRecord, setViewRecord] = useState({});
  const [instanceViewOpen, setInstanceViewOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  const [editRecord, setEditRecord] = useState({});

  // current 默认为1 不传也是为1
  const getCurrentTableList = async (keyword, chunkSize, current = 1, targetTable, taskId) => {
    setState({ pageLoading: true });
    if (targetTable) {
      const res = await taskInstanceList({
        currentPage: current,
        keyword: keyword,
        size: chunkSize,
        taskId: taskId,
      });
      if (res.data) {
        setState({
          keyword: keyword,
          tableDataSource: _.cloneDeep(res?.data),
          pagination: {
            current: res?.current,
            pageSize: res?.size,
            total: res?.total,
          },
          pageLoading: false,
        });
      } else {
        message.error('获取实例列表数据失败!' + res?.message);
        setState({
          tableDataSource: state.tableDataSource,
          pageLoading: false,
        });
      }
      setState({ keyword: '' });
    } else {
      const res = await taskTableData({
        currentPage: current,
        keyword: keyword,
        size: chunkSize,
      });
      if (res.data) {
        setState({
          keyword: keyword,
          tableDataSource: _.cloneDeep(res?.data),
          pagination: {
            current: res?.current,
            pageSize: res?.size,
            total: res?.total,
          },
          pageLoading: false,
        });
      } else {
        message.error('获取任务列表数据失败!' + res?.message);
        setState({
          tableDataSource: state.tableDataSource,
          pageLoading: false,
        });
      }
      setState({ keyword: '' });
    }
  };

  const getFilterTableList = (formValue) => {
    const current = 1;
    getCurrentTableList(
      formValue,
      state.pagination.pageSize,
      current,
      state.instanceOpen,
      state.taskId,
    );
  };

  const showDrawer = () => {
    setOpen(true);
  };

  const onClose = () => {
    setOpen(false);
  };

  const showViewDrawer = async ({ taskId, id }, rowIndex) => {
    if (taskId) {
      await taskDetail(taskId)
        .then((res) => {
          if (res.statusCode === '1000') {
            setViewRecord({ ...res.data });
            setViewOpen(true);
          } else {
            message.error(res.message);
          }
        })
        .catch((res) => message.error(res.message));
    }
    if (id) {
      await taskInstanceDetail(id)
        .then((res) => {
          if (res.statusCode === '1000') {
            setViewRecord({ ...res.data });
            setInstanceViewOpen(true);
          } else {
            message.error(res.message);
          }
        })
        .catch((res) => message.error(res.message));
    }
  };

  const onViewClose = () => {
    setViewOpen(false);
  };

  const onInstanceViewOpen = () => {
    setInstanceViewOpen(false);
  };

  const showEditDrawer = async ({ taskId }, rowIndex) => {
    if (taskId) {
      await taskDetail(taskId)
        .then((res) => {
          if (res.statusCode === '1000') {
            setEditOpen(true);
            setEditRecord({ ...res.data });
          } else {
            message.error(res.message);
          }
        })
        .catch((res) => message.error(res.message));
    }
  };

  const onEditClose = () => {
    setEditOpen(false);
  };

  const openInstanceList = (record, rowIndex) => {
    handleSearchReset();
    const taskId = record?.taskId;
    const newInstanceOpen = true;
    setState({ instanceOpen: newInstanceOpen, keyword: '', tableDataSource: [], taskId: taskId });
    getCurrentTableList(
      state.keyword,
      state.pagination.pageSize,
      state.pagination.current,
      newInstanceOpen,
      taskId,
    );
  };

  const onInstanceClose = () => {
    handleSearchReset();
    const newInstanceOpen = false;
    setState({ instanceOpen: newInstanceOpen, keyword: '', tableDataSource: [] });
    getCurrentTableList(
      state.keyword,
      state.pagination.pageSize,
      state.pagination.current,
      newInstanceOpen,
    );
    onInstanceViewOpen();
  };

  const handleTopSearchSubmit = (formValue) => {
    getFilterTableList(formValue);
  };

  const handleChangeTablePage = (current, pageSize) => {
    getCurrentTableList(state.keyword, pageSize, current, state.instanceOpen, state.taskId);
  };

  const onChangeTableStatus = async ({ deploymentStatus, taskId }, rowIndex) => {
    if (deploymentStatus === false) {
      await deployTask(taskId)
        .then((res) => {
          if (res.statusCode === '1000') {
            message.success('部署成功');
          } else {
            message.error(res.message);
          }
        })
        .catch((res) => message.error(res.message));
    } else if (deploymentStatus === true) {
      await undeploy(taskId)
        .then((res) => {
          if (res.statusCode === '1000') {
            message.success('取消部署成功');
          } else {
            message.error(res.message);
          }
        })
        .catch((res) => message.error(res.message));
    }

    getCurrentTableList(state.keyword, state.pagination.pageSize, state.pagination.current); // 修改时页面分页不变化

    setState({
      tableDataSource: state.tableDataSource,
    });
  };

  const handleDeleteTableRow = ({ taskId }) => {
    confirm({
      title: '确定删除此行数据吗?',
      icon: <ExclamationCircleOutlined />,
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      async onOk() {
        await deleteTask(taskId)
          .then((res) => {
            if (res.statusCode === '1000') {
              message.success('删除成功');
            } else {
              message.error(res.message);
            }
          })
          .catch((res) => message.error(res.message));
        getCurrentTableList(state.keyword, state.pagination.pageSize, state.pagination.current); // 删除时页面分页不变化
        setState({ tableDataSource: state.tableDataSource });
      },
    });
  };

  const handleCreateSubmit = async (formValue) => {
    try {
      if (!formValue.formType) {
        if (!formValue.companyList || formValue.companyList.length === 0) {
          message.warning('请选择公司');
          return null;
        }

        if (!formValue.grabModuleList || formValue.grabModuleList.length === 0) {
          message.warning('请选择模块');
          return null;
        }

        const formData = {
          actuatorTypeCode: formValue.actuatorTypeCode,
          companyList: formValue.companyList?.map(({ companyCode }, index) => ({ companyCode })),
          cronTime: formValue.cronTime,
          // dataProcess: formValue.dataProcess,
          executeScript: formValue.executeScript,
          grabModuleList: formValue.grabModuleList?.map(({ grabModuleCode }, index) => ({
            grabModuleCode,
          })),
          maxRetryCount: formValue.maxRetryCount,
          priority: formValue.priority,
          retry: formValue.retry,
          retryTime: Number(formValue.retryTime),
          timeOut: formValue.timeOut,
          retryTypeCode: formValue.retryType,
          taskDesc: formValue.taskDesc,
          taskName: formValue.taskName,
          tradingCenterCode: formValue.tradingCenterCode,
          valid: formValue.valid,
          dataName: formValue.dataName,
          checkField: formValue.checkField,
          deleteField: formValue.deleteField,
          clickhouseName: formValue.clickhouseName,
        };

        await addTask(formData)
          .then((res) => {
            if (res.statusCode === '1000') {
              message.success('新增成功');
              setOpen(false);
              setReset(true);
              getCurrentTableList(
                state.keyword,
                state.pagination.pageSize,
                state.pagination.current,
              );
              setState({ tableDataSource: state.tableDataSource });
            } else {
              message.error(res.message);
            }
          })
          .catch((res) => message.error(res.message));
      } else {
        if (!formValue.companyList || formValue.companyList.length === 0) {
          message.warning('请选择公司');
          return null;
        }

        if (!formValue.grabModuleList || formValue.grabModuleList.length === 0) {
          message.warning('请选择模块');
          return null;
        }
        const formData = {
          taskId: formValue.taskId,
          actuatorTypeCode: formValue.actuatorTypeCode,
          companyList: formValue.companyList?.map(({ companyCode }, index) => ({ companyCode })),
          cronTime: formValue.cronTime,
          // dataProcess: formValue.dataProcess,
          executeScript: formValue.executeScript,
          grabModuleList: formValue.grabModuleList?.map(({ grabModuleCode }, index) => ({
            grabModuleCode,
          })),
          maxRetryCount: formValue.maxRetryCount,
          priority: formValue.priority,
          retry: formValue.retry,
          retryTime: Number(formValue.retryTime),
          timeOut: formValue.timeOut,
          retryTypeCode: formValue.retryType,
          taskDesc: formValue.taskDesc,
          taskName: formValue.taskName,
          tradingCenterCode: formValue.tradingCenterCode,
          valid: formValue.valid,
          dataName: formValue.dataName,
          checkField: formValue.checkField,
          deleteField: formValue.deleteField,
          clickhouseName: formValue.clickhouseName,
        };
        await updateTask(formData)
          .then((res) => {
            if (res.statusCode === '1000') {
              message.success('任务编辑成功');
              setEditOpen(false);
              setReset(true);
              getCurrentTableList(
                state.keyword,
                state.pagination.pageSize,
                state.pagination.current,
              );
              setState({ tableDataSource: state.tableDataSource });
            } else {
              message.error(res.message);
            }
          })
          .catch((res) => message.error(res.message));
      }
    } catch (error) {
      message.error(error);
      return false;
    }
  };

  const handleCreateDR = () => {
    return (
      <DRBox
        className={styles.drawerContent}
        handleCreateSubmit={handleCreateSubmit}
        handleReset={reset}
        formType="create"
      >
        {(form) => <DRFormItem form={form} formType="create" isVertical handleReset={reset} />}
      </DRBox>
    );
  };

  const handleViewDR = () => {
    return (
      <DRBox
        className={styles.drawerContent}
        formType="view"
        viewRecord={viewRecord}
        onInstanceClose={onInstanceClose}
      >
        {(form) => <DRFormItem form={form} formType="view" isVertical viewRecord={viewRecord} />}
      </DRBox>
    );
  };

  const handleInstanceViewDR = () => {
    return (
      <DRBox
        className={styles.drawerContent}
        formType="instanceView"
        viewRecord={viewRecord}
        onInstanceClose={onInstanceClose}
      >
        {(form) => (
          <DRFormItem form={form} formType="instanceView" isVertical viewRecord={viewRecord} />
        )}
      </DRBox>
    );
  };

  const handleEditDR = () => {
    return (
      <DRBox
        className={styles.drawerContent}
        handleCreateSubmit={handleCreateSubmit}
        formType="edit"
      >
        {(form) => <DRFormItem form={form} formType="edit" isVertical editRecord={editRecord} />}
      </DRBox>
    );
  };

  const handleSearchReset = () => {
    if (searchResetRef.current) {
      searchResetRef.current();
    }
  };

  const topSearchFormTemplate = () => {
    return (
      <HeadBox>
        {(form, searchReset) => {
          searchResetRef.current = searchReset;
          return (
            <LinkedFormItem
              form={form}
              handleSearchSubmit={handleTopSearchSubmit}
              formType="search"
            />
          );
        }}
      </HeadBox>
    );
  };

  const operationsBtnTemplate = () => {
    return (
      <div className={styles.pageTitle}>
        {state.instanceOpen === false ? <h4>任务管理</h4> : <h4>实例列表</h4>}
        <div>
          <Button
            style={{ marginRight: '16px', width: '98px' }}
            // onClick={() => handleCreateDialog()}
          >
            导出
          </Button>
          {state.instanceOpen === false ? (
            <Button style={{ width: '98px' }} type="primary" onClick={showDrawer}>
              新建
            </Button>
          ) : (
            <Button style={{ width: '98px' }} type="primary" onClick={onInstanceClose}>
              返回
            </Button>
          )}
        </div>
      </div>
    );
  };

  const handleChangeTableSelect = (nextValue) => {
    // console.log('nextValue', nextValue);
    nextValue.length > 0
      ? setState({ selectedRowKeys: nextValue })
      : setState({ selectedRowKeys: [] });
    // console.log('selectedRowKeys', state.selectedRowKeys);
  };
  const handleChangeTableSelect1 = (nextValue) => {
    // console.log('nextValue', nextValue);
    nextValue.length > 0
      ? setState({ selectedRowKeys1: nextValue })
      : setState({ selectedRowKeys1: [] });
  };

  return (
    <Spin spinning={state.pageLoading}>
      <div className={styles.pageContainer}>
        {topSearchFormTemplate()}
        <div className={styles.pageContent}>
          <div className={styles.pageBody}>
            {operationsBtnTemplate()}
            {state.instanceOpen === false ? (
              <TRTable
                columns={TABLE_COLUMNS_LIST({
                  buttonPermissionCode,
                  onChangeTableStatus,
                  handleDeleteTableRow,
                  pagination: state.pagination,
                  showEditDrawer,
                  showViewDrawer,
                  openInstanceList,
                })}
                hasPagination
                style={{ height: 'calc(100vh - 360px)', minHeight: '300px' }}
                tableData={state.tableDataSource}
                paginationConfig={state.pagination}
                onChangePage={handleChangeTablePage}
                hasMultiSelect
                checkValue={state.selectedRowKeys}
                handleChange={handleChangeTableSelect}
              />
            ) : (
              <TRTable
                columns={IN_TABLE_COLUMNS_LIST({
                  showViewDrawer,
                  onInstanceClose,
                })}
                hasPagination
                style={{ height: 'calc(100vh - 360px)', minHeight: '300px' }}
                tableData={state.tableDataSource}
                paginationConfig={state.pagination}
                onChangePage={handleChangeTablePage}
                hasMultiSelect1
                checkValue={state.selectedRowKeys1}
                handleChange1={handleChangeTableSelect1}
              />
            )}
            <Drawer title="新建任务" width={1164} onClose={onClose} visible={open}>
              {handleCreateDR()}
            </Drawer>
            <Drawer title="查看任务" width={1164} onClose={onViewClose} visible={viewOpen}>
              {handleViewDR()}
            </Drawer>
            <Drawer
              title="查看实例任务"
              width={1164}
              onClose={onInstanceViewOpen}
              visible={instanceViewOpen}
            >
              {handleInstanceViewDR()}
            </Drawer>
            <Drawer title="编辑任务" width={1164} onClose={onEditClose} visible={editOpen}>
              {handleEditDR()}
            </Drawer>
          </div>
        </div>
      </div>
    </Spin>
  );
};

export default connect(({ global }) => ({
  menuCode: global?.configure?.menuCode || '',
}))(TaskAdmin);
